package cn.aishua.ui.myKaka;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cn.aishua.R;
import cn.aishua.R.drawable;
import cn.aishua.data.DatabaseOperator;
import cn.aishua.data.FavoriteItem;
import cn.aishua.ui.vendor.VendorDetailActivity;
import cn.aishua.util.FormatConverter;
import cn.aishua.util.ImageLoader;

public class MyFavoriteActivity
    extends ListActivity
{

    private ArrayList<FavoriteItem> favoriteData;

    // page header widgets
    private ImageView ivLeftBtn;
    private ImageView ivRightBtn;
    private TextView tvTitile;

    private void initPageHeader()
    {
        // left button
        ivLeftBtn = (ImageView) findViewById( R.id.page_header_iv_left_btn );
        ivLeftBtn.setImageResource( R.drawable.btn_back );
        ivLeftBtn.setOnClickListener( new View.OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                onBackPressed();
            }
        } );

        // title
        tvTitile = (TextView) findViewById( R.id.page_header_tv_title );
        tvTitile.setText( "我的收藏" );

        // right button
        ivRightBtn = (ImageView) findViewById( R.id.page_header_iv_right_btn );
        ivRightBtn.setImageResource( R.drawable.button_gar_normal );
        ivRightBtn.setOnClickListener( new View.OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                clean();
            }
        } );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.my_kaka_my_favorite );
        initPageHeader();
        initiate();

    }

    private void initiate()
    {

        final ListView listView = getListView();

        FavoriteAdapter adapter = new FavoriteAdapter();
        listView.setAdapter( adapter );
        listView.setOnCreateContextMenuListener( new OnCreateContextMenuListener()
        {

            @Override
            public void onCreateContextMenu( ContextMenu menu, View v, ContextMenuInfo menuInfo )
            {
                int position = ( (AdapterContextMenuInfo) menuInfo ).position;
                FavoriteItem item = (FavoriteItem) listView.getItemAtPosition( position );
                String vendorNamej = item.getVendorName();
                menu.setHeaderTitle( vendorNamej );
                menu.add( 0, Menu.FIRST, 0, "查看商户详情" );
                menu.add( 0, Menu.FIRST + 1, 0, "从收藏里删除" );
            }
        } );

        //        listView.setDividerHeight( 5 );
        //        listView.setDivider( new ColorDrawable( R.color.d9d9d9 ) );
    }

    @Override
    public boolean onContextItemSelected( MenuItem item )
    {

        final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        final int position = (int) info.position;

        if( -1 == position )
        {
            super.onContextItemSelected( item );

        }
        int vendorId = ( (FavoriteItem) getListView().getItemAtPosition( position ) ).getId();

        switch( item.getItemId() )
        {
            case Menu.FIRST:
                Intent intent = new Intent( this, VendorDetailActivity.class );
                intent.putExtra( VendorDetailActivity.EXTRA_INT_MERCHANT_ID, vendorId );
                startActivity( intent );
                break;
            case Menu.FIRST + 1:
                if( DatabaseOperator.getInstance().removeFavorite( vendorId ) )
                {
                    favoriteData.remove( position );
                    ( (FavoriteAdapter) getListView().getAdapter() ).notifyDataSetChanged();
                }

                break;
        }
        return super.onContextItemSelected( item );
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        retrieveFavoriteData();
    }

    private void retrieveFavoriteData()
    {
        new AsyncTask<Void, Void, ArrayList<FavoriteItem>>()
        {

            @Override
            protected ArrayList<FavoriteItem> doInBackground( Void... params )
            {
                SQLiteDatabase db = DatabaseOperator.getInstance().openDb();
                Cursor cursor = db.query( DatabaseOperator.TBL_NAME_FAVORITE, new String[] { "id", "vendor_name",
                        "average_price", "distance", "tags", "rebate", "pic_url" }, null, null, null, null, null );
                ArrayList<FavoriteItem> fovoriteList = new ArrayList<FavoriteItem>();
                while( cursor.moveToNext() )
                {

                    fovoriteList.add( new FavoriteItem( cursor.getInt( 0 ), cursor.getString( 1 ),
                        cursor.getString( 2 ), cursor.getString( 3 ), cursor.getString( 4 ), cursor.getString( 5 ),
                        cursor.getString( 6 ) ) );
                }
                cursor.close();
                db.close();

                return fovoriteList;
            }

            @Override
            protected void onPostExecute( ArrayList<FavoriteItem> result )
            {
                favoriteData = result;
                ( (FavoriteAdapter) getListView().getAdapter() ).notifyDataSetChanged();
            }
        }.execute();
    }

    public void toCreditExchangePage( View view )
    {
        Intent toCreditExchangePage = new Intent( this, CreditExchangeActivity.class );

        startActivity( toCreditExchangePage );
    }

    public void clean()
    {
        new AlertDialog.Builder( this ).setTitle( "确定清空收藏夹?" ).setMessage( null )
            .setPositiveButton( "确定", new OnClickListener()
            {

                public void onClick( DialogInterface dialog, int which )
                {
                    // only refresh view when clean happens
                    if( DatabaseOperator.getInstance().cleanFavorite() )
                    {
                        favoriteData.clear();
                        ( (FavoriteAdapter) getListView().getAdapter() ).notifyDataSetChanged();
                    }
                }
            } ).setNegativeButton( "取消", null ).show();
    }

    class ViewHolder
    {
        public int id;
        public TextView tvVendorName;
        public TextView tvAveragePrice;
        public TextView tvDistance;
        public TextView tvTags;
        public TextView tvRebate;
        public ImageView ivPic;
    }

    class FavoriteAdapter
        extends BaseAdapter
    {

        public int getCount()
        {
            if( favoriteData != null )
            {
                return favoriteData.size();
            }
            else
            {
                return 0;
            }
        }

        public Object getItem( int position )
        {
            return favoriteData.get( position );
        }

        public long getItemId( int position )
        {
            return position;
        }

        public View getView( int position, View convertView, ViewGroup parent )
        {
            Log.d( "generate list view", "position - " + position );
            ViewHolder viewHolder = null;
            LayoutInflater inflater = LayoutInflater.from( MyFavoriteActivity.this );

            if( convertView == null )
            {
                convertView = inflater.inflate( R.layout.vendor_item, null );

                // This holder contains three widgets of credit item
                viewHolder = new ViewHolder();
                viewHolder.tvVendorName = (TextView) convertView.findViewById( R.id.vendor_item_tv_vendor_name );
                viewHolder.tvAveragePrice = (TextView) convertView.findViewById( R.id.vendor_item_tv_average_price );
                viewHolder.tvDistance = (TextView) convertView.findViewById( R.id.vendor_item_tv_distance );
                viewHolder.tvTags = (TextView) convertView.findViewById( R.id.vendor_item_tv_tags );
                viewHolder.tvRebate = (TextView) convertView.findViewById( R.id.vendor_item_tv_rebate );
                viewHolder.ivPic = (ImageView) convertView.findViewById( R.id.vendor_item_iv_pic );

                convertView.setTag( viewHolder );
            }
            else
            {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            Log.d( "generate list view", "vendor: " + favoriteData.get( position ).getVendorName() );
            FavoriteItem item = favoriteData.get( position );

            viewHolder.id = item.getId();
            viewHolder.tvVendorName.setText( item.getVendorName() );
            viewHolder.tvAveragePrice.setText( item.getAveragePrice() );
            viewHolder.tvDistance.setText( item.getDistance() );
            viewHolder.tvTags.setText( item.getTags() );
            viewHolder.tvRebate.setText( item.getRebate().replace( "%", "" ) );

            String picUrl = item.getPicUrl();
            if( FormatConverter.isNotEmptyString( picUrl ) )
            {
//                viewHolder.ivPic.setImageBitmap( BitmapFactory.decodeByteArray( item.getPicture(), 0,
//                    item.getPicture().length ) );
                ImageLoader.getInstance( MyFavoriteActivity.this ).loadImage( picUrl, viewHolder.ivPic );
            }
            // set background
            if( position % 2 == 1 )
            {
                convertView.setBackgroundResource( drawable.list_item_bg_color_2 );
            }
            else
            {
                convertView.setBackgroundResource( drawable.list_item_bg_color_1 );
            }

            return convertView;
        }
    }

    public void toVendorDetail( View view )
    {
        Intent intent = new Intent( this, VendorDetailActivity.class );
        ViewHolder holder = (ViewHolder) view.getTag();
        intent.putExtra( VendorDetailActivity.EXTRA_INT_MERCHANT_ID, holder.id );
        startActivity( intent );
    }
}
